﻿@inherits LayoutComponentBase
@inject GlobalConfig GlobalConfig
@inject AuthenticationStateProvider AuthenticationStateProvider
@inject NavigationManager NavigationManager
@inject LocalStorageJsInterop LocalStorageJsInterop

<MApp>
    <PPageTabsProvider>
        <CascadingValue Value="GlobalConfig.Culture.Name" Name="CultureName">
            <MAppBar Elevation=0 App Height="100" Class="default-app-bar mx-6">
                <div class="default-app-bar__actions page-mode--tab">
                    <MSpacer />
                    <Language OnLanguageChanged="OnLanguageChanged" />
                    <Login />
                </div>
                <div class="default-app-bar__nav page-mode--tab">
                    <PageTabs @ref="_pageTabs" />
                </div>
            </MAppBar>

            <Navigation />

            <MMain Class="fill-lighten-1">
                <div class="pa-6">
                    <PPageContainer PageTabs="@_pageTabs?.PPageTabs">
                        @Body
                    </PPageContainer>
                </div>
            </MMain>
        </CascadingValue>
    </PPageTabsProvider>
</MApp>

<MButton Dark Fab Fixed Bottom Right Href="https://github.com/239573049/fast-wiki" >
    <MIcon>mdi-github</MIcon>
</MButton>

@code {

    private PageTabs? _pageTabs;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            var state = await AuthenticationStateProvider.GetAuthenticationStateAsync();

            if (state.User.Identity?.IsAuthenticated == false)
            {
                NavigationManager.NavigateTo("/pages/authentication/Login",true);

                return;
            }
            else
            {
                var token = await LocalStorageJsInterop.GetLocalStorageAsync(Constant.Token);
                ((WikiAuthenticationStateProvider)AuthenticationStateProvider)
                    .AuthenticateUser(token);
            }

            await GlobalConfig.InitFromStorage();
        }
    }

    void OnLanguageChanged(CultureInfo culture)
    {
        GlobalConfig.Culture = culture;
    }
}
